package waitandnotify;
class Emotion implements Runnable {

    private Object object;//要上锁的对象。

    private String type; //表情的类型

    public Emotion(Object object, String type) {
        this.object = object;
        this.type = type;
    }

    @Override
    public void run() {

        synchronized (object) {
            if ("^_^".equals(type)) {
                for (int i = 1; i <= 50; i++) {
                    System.out.println("^_^");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (i % 10 == 0 && i<50) {
                        object.notify();
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    if(i==50){
                        object.notify(); //退出循环前，仅仅需要notify
                    }
                }

            } else {
                for (int i = 1; i <= 50; i++) {
                    System.out.println("@_@");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (i % 10 == 0 && i<50) {
                        object.notify();
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    if(i==50){
                        object.notify(); //退出循环前，仅仅需要notify
                    }
                }

            }
        }

    }
}

public class EmotionDemo {

    public static void main(String[] args) {
        Object object = new Object(); //上锁的对象。

        Emotion smile = new Emotion(object, "^_^");
        Emotion amaze = new Emotion(object, "@_@");

        Thread smileThread = new Thread(smile);
        Thread amazeThread = new Thread(amaze);

        smileThread.start();
        amazeThread.start();
    }
}
